package com.nuo.modules.teacher.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuo.common.excel.po.ExportListPo;
import com.nuo.common.excel.service.ExcelService;
import com.nuo.common.exception.GlobalException;
import com.nuo.common.threadlocal.ThreadLocalDemo;
import com.nuo.common.utils.Constant;
import com.nuo.common.utils.PageUtils;
import com.nuo.common.utils.Query;
import com.nuo.common.utils.R;
import com.nuo.modules.signRecord.entity.SignRecordEntity;
import com.nuo.modules.signRecord.service.SignRecordService;
import com.nuo.modules.sys.service.SysUserTokenService;
import com.nuo.modules.teacher.dao.TeacherDao;
import com.nuo.modules.teacher.entity.TeacherEntity;
import com.nuo.modules.teacher.po.LoginPo;
import com.nuo.modules.teacher.po.SignPo;
import com.nuo.modules.teacher.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("teacherService")
@Slf4j
public class TeacherServiceImpl extends ServiceImpl<TeacherDao, TeacherEntity> implements TeacherService {

    @Autowired
    ThreadLocalDemo threadLocalDemo;

    @Autowired
    SysUserTokenService sysUserTokenService;

    @Autowired
    SignRecordService signRecordService;

    @Autowired
    private ExcelService<TeacherEntity, TeacherService> excelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String name =(String) params.get("username");
        IPage<TeacherEntity> page = this.page(
                new Query<TeacherEntity>().getPage(params),
                new QueryWrapper<TeacherEntity>().lambda().like(StringUtils.isNotBlank(name), TeacherEntity::getUsername, name)
        );

        return new PageUtils(page);
    }

    @Override
    public R login(LoginPo po) {
        String phone = po.getPhone();
        String password= new Sha256Hash(po.getPassword(), Constant.TSALT).toHex();
        TeacherEntity one = getOne(
                new LambdaQueryWrapper<TeacherEntity>()
                        .eq(TeacherEntity::getTelephone, phone)
                        .eq(TeacherEntity::getPassword,password)
        );
        R res;
        if (one==null) {
            throw new  GlobalException("手机号或密码错误");
        }else {
            res = sysUserTokenService.createToken(one.getId(), 2);
        }
        return res;
    }

    @Override
    public R sign(SignPo po, HttpServletRequest request) {
        log.warn("sessionId: " + request.getSession().getId());
        List<TeacherEntity> list = list(new LambdaQueryWrapper<TeacherEntity>()
                .eq(TeacherEntity::getSchool, po.getSchool())
                .eq(TeacherEntity::getClassName, po.getClassName())
                .eq(TeacherEntity::getUsername, po.getUsername())
        );
        if (list != null && !list.isEmpty()) {
            request.getSession().setAttribute("sign", true);
            TeacherEntity teacherEntity = list.get(0);
            SignRecordEntity signRecordEntity = BeanUtil.copyProperties(teacherEntity, SignRecordEntity.class);
            Date date = new Date();
            signRecordEntity.setCreateTime(date);

            //获取当天时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String day = sdf.format(new Date());

            // 获取当天是否签到了
            SignRecordEntity one = signRecordService.getOne(new LambdaQueryWrapper<SignRecordEntity>()
                    .eq(SignRecordEntity::getTeacherId, teacherEntity.getTeacherId())
                    .like(SignRecordEntity::getCreateTime, day)
            );

            if (one!=null){
                return R.ok("今日已签到");
            }else {
                // 没签到去签到
                signRecordService.save(signRecordEntity);
                return R.ok();
            }

        } else {
            return R.error(404, "信息填写有误...");
        }
    }

    @Override
    public R importList(MultipartFile file) {
        List<TeacherEntity> list = list();
        return excelService.importList(file, TeacherEntity.class, this,list);
    }

    @Override
    public R exportList(ExportListPo<TeacherEntity> po) {
        return excelService.exportList(po, TeacherEntity.class);
    }

    @Override
    public R exportAll() {
        return excelService.exportAll(TeacherEntity.class, this);
    }


    @Override
    public void saveOrUpdateBatch(List<TeacherEntity> list, Class<TeacherEntity> clazz) {
        saveOrUpdateBatch(list, "teacher_id", "teacherId", clazz);
    }
}
